package com.hospital.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.yygh.cmn.listener.DictListener;
import com.hospital.yygh.cmn.mapper.DictMapper;
import com.hospital.yygh.cmn.service.DictService;
import com.hospital.yygh.model.cmn.Dict;
import com.hospital.yygh.vo.cmn.DictEeVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 添加SpringCache缓存，在common模块下service-utils中配置RedisConfig
 *
 * @Cacheable ：缓存存在，下次请求直接读取缓存的数据，否则执行方法，读取数据库文件数据（一般用在查询上）
 * @CachePut ：每次都执行，存入缓存，其他方法从响应的缓存中读取缓存数据，不需要在查数据库（一般用于新增方法）
 * @CacheEvict：清空指定缓存（一般用于更新和删除方法上） 测试：重新启动该项目，刷新页面，查看Linux中Redis客户端的数据(keys *)
 * 需要关闭Linux防火墙：systemctl stop firewalld
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    // 日志
    private final static Logger logger = LoggerFactory.getLogger(DictServiceImpl.class);

    @Autowired(required = false)
    private DictMapper dictMapper;

    /**
     * 判断id下面是否有子节点
     *
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        // 0>0:false 1>0:true
        return count > 0;
    }

    /**
     * 根据数据id查询子数据列表
     *
     * @param id
     * @return
     * @Cacheable: 添加缓存
     */
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        // 向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    /**
     * 导出数据字典
     *
     * @param response
     */
    @Override
    public void exportDictData(HttpServletResponse response) {
        // 设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        // 把Dict对象转换成DictEeVo对象
        List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictVoList.add(dictEeVo);
        }
        // 调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 导入数据字典
     *
     * @param file
     * @CacheEvict: 表示清空缓存中的所有内容
     */
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(dictMapper))
                    .sheet()
                    .doRead();
            logger.info("上传成功");
        } catch (IOException e) {
            logger.info("上传失败");
            e.printStackTrace();
        }
    }

    /**
     * 根据dictCode和value查询
     *
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getDictName(String dictCode, String value) {
        // 如果dictCode为空,直接根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> wrapper = new QueryWrapper();
            wrapper.eq("value", value);
            Dict dict = dictMapper.selectOne(wrapper);
            if (null != dict) {
                return dict.getName();
            }
        } else {
            // 如果dictCode不为空,根据dictCode和value查询
            // 根据dictcode查询dict对象，目的是得到dict的id值，在根据此id值查询此id下的子id
            QueryWrapper<Dict> wrapper1 = new QueryWrapper();
            wrapper1.eq("dict_code", dictCode);
            Dict codeDict = dictMapper.selectOne(wrapper1);
            if (null == codeDict) {
                return "";
            }
            Long parent_id = codeDict.getId();
            // 根据parentId和value值进行查询
            QueryWrapper<Dict> wrapper2 = new QueryWrapper();
            wrapper2.eq("parent_id", parent_id).eq("value", value);
            Dict finalDict = baseMapper.selectOne(wrapper2);
            if (null != finalDict) {
                return finalDict.getName();
            }
        }
        return "";
    }

    /**
     * 根据dictCode获取下级节点
     *
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 根据dictcode获取对应的id
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("dict_code", dictCode);
        Dict codeDict = dictMapper.selectOne(wrapper);
        // 根据id获取下级子节点
        List<Dict> childData = this.findChildData(codeDict.getId());
        return childData;
    }


}
